import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/vg_text_field.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

/// 登录页-手机号输入框
///
/// @author: zengxiangxi
/// @createTime: 1/6/21 3:00 PM
/// @specialDemand:
class LoginIndexEditPhoneWidget extends StatefulWidget {

  final ValueNotifier<String> phoneValueNotifier;

  const LoginIndexEditPhoneWidget({Key key,@required this.phoneValueNotifier}) : super(key: key);
  
  @override
  _LoginIndexEditPhoneWidgetState createState() =>
      _LoginIndexEditPhoneWidgetState();
}

class _LoginIndexEditPhoneWidgetState extends BaseState<LoginIndexEditPhoneWidget> {
  TextEditingController _editingController;

  ValueNotifier<bool> _isShowHintTextNotifier;

  ValueNotifier<bool> _isShowDeleteValueNotifier;

  FocusNode _focusNode;

  @override
  void initState() {
    super.initState();
    _editingController = TextEditingController();
    _isShowHintTextNotifier = ValueNotifier(true);
    _isShowDeleteValueNotifier =
        ValueNotifier(StringUtils.isNotEmpty(_editingController?.text));
    _focusNode = FocusNode();
    _focusNode.addListener(() {
      if(_focusNode.hasFocus || StringUtils.isNotEmpty(_editingController?.text)){
        _isShowHintTextNotifier.value = false;
      }else{
        _isShowHintTextNotifier.value = true;
      }
      if(_focusNode.hasFocus || StringUtils.isNotEmpty(_editingController?.text)){
        _isShowDeleteValueNotifier.value = true;
      }else{
        _isShowDeleteValueNotifier.value = false;
      }
    });
  }

  @override
  void dispose() {
    _editingController?.dispose();
    _isShowHintTextNotifier?.dispose();
    _isShowDeleteValueNotifier?.dispose();
    _focusNode?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 50,
      margin: const EdgeInsets.symmetric(horizontal: 46),
      decoration: BoxDecoration(
          color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
          borderRadius: BorderRadius.circular(25)),
      alignment: Alignment.center,
      child: Stack(
        fit: StackFit.expand,
        children: <Widget>[
          _toHintTextWidget(),
          _toPhoneEditTextWidget(),
          Positioned(
            top: 15,
            right: 5,
            child: _toDeleteIcon(),
          ),
        ],
      ),
    );
  }

  ///提示语
  Widget _toHintTextWidget() {
    return ValueListenableBuilder(
      valueListenable: _isShowHintTextNotifier,
      builder: (BuildContext context, bool isShow, Widget child){
        return Offstage(
          offstage: !isShow,
          child: child,
        );
      },
      child: Center(
        child: Text(
          "输入手机号",
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
              color: VgColors.INPUT_BG_COLOR,
              fontSize: 17,
              height: 1.2,
          ),
        ),
      ),
    );
  }

  ///手机号编辑
  Widget _toPhoneEditTextWidget() {
    return VgTextField(
      controller: _editingController,
      focusNode: _focusNode,
      keyboardType: TextInputType.number,
      textAlign: TextAlign.center,
      maxLines: 1,
      autofocus: false,
      cursorWidth: 2,
      cursorRadius: Radius.circular(5),
      inputFormatters: [
        WhitelistingTextInputFormatter(RegExp("[0-9+]")),
        LengthLimitingTextInputFormatter(DEFAULT_PHONE_LENGTH_LIMIT)
      ],
      decoration: InputDecoration(
        border: InputBorder.none,
        counterText: "",
        contentPadding: const EdgeInsets.only(top: 2),
        hintText: "",
        hintStyle: TextStyle(
            color: ThemeRepository.getInstance().getTextEditHintColor_3A3F50(),
            fontSize: 22),
      ),
      style: TextStyle(
          fontSize: 22,
          fontWeight: FontWeight.w600,
          color: ThemeRepository.getInstance().getTextMainColor_D0E0F7()),
      onChanged: (String completePhone){
        _changeEditStatus(completePhone);
      },
    );
  }

  ///清除按钮
  Widget _toDeleteIcon() {
    return ValueListenableBuilder(
      valueListenable: _isShowDeleteValueNotifier,
      builder: (BuildContext context, bool isShow, Widget child) {
        return AnimatedSwitcher(
          duration: DEFAULT_ANIM_DURATION,
          child: isShow ? child : Container(),
        );
      },
      child: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          _editingController?.clear();
          _changeEditStatus("");
          // VgToolUtils.removeAllFocus(context);
          FocusScope.of(context).requestFocus(_focusNode);
          setState(() { });
        },
        child: Padding(
          padding: const EdgeInsets.only(left: 8,right: 20,top: 3,bottom: 3),
          child: Container(
            width: 17,
            height: 17,
            decoration: BoxDecoration(
                shape: BoxShape.circle, color: Colors.white.withOpacity(0.1)),
            child: Icon(
              Icons.close,
              size: 11,
              color: ThemeRepository.getInstance()
                  .getTextMainColor_D0E0F7()
                  .withOpacity(0.8),
            ),
          ),
        ),
      ),
    );
  }
  
  void _changeEditStatus(String completePhone){
    if(widget?.phoneValueNotifier != null){
      String normalPhone;
      if(completePhone != null && completePhone.length > DEFAULT_PHONE_LENGTH_LIMIT){
        normalPhone = completePhone?.substring(0,DEFAULT_PHONE_LENGTH_LIMIT);
      }else{
        normalPhone = completePhone;
      }
      widget.phoneValueNotifier.value = normalPhone;
    }
  }
}
